package com.zhiyou100.dao;

import cn.hutool.core.date.DateUtil;
import com.sun.org.apache.regexp.internal.RE;
import com.zhiyou100.entity.Student;
import com.zhiyou100.util.JdbcUtil;
import lombok.SneakyThrows;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * Student dao层
 *
 * @author yang
 * @version 1.0.0
 * @date 2020-09-15 15:59
 */
public class StudentDao {
    /**
     * 插入一个学生
     *
     * @param student 要插入的学生没有 sid
     * @return 收到影响的行数
     */
    @SneakyThrows
    public int insertOne(Student student) {
        // 获取连接
        final Connection con = JdbcUtil.getConnection();
        // 发送模版
        final PreparedStatement pre = con.prepareStatement("insert into student values(student_seq.nextval,?,?,?,?)");
        // 设置模版参数
        pre.setString(1, student.getSname());
        pre.setInt(2, student.getSage());
        pre.setFloat(3, student.getScore());
        pre.setTimestamp(4, DateUtil.date(student.getSbirthday()).toTimestamp());
        // 执行语句，获取返回值
        final int hang = pre.executeUpdate();
        // 关闭连接
        JdbcUtil.close(con, null, pre);
        return hang;
    }

    /**
     * 获取所有的学生
     *
     * @return list<Student>
     */
    @SneakyThrows
    public List<Student> listStudent() {
        final ArrayList<Student> students = new ArrayList<>();
        // 获取连接
        final Connection con = JdbcUtil.getConnection();
        // 发送模版
        final PreparedStatement pre = con.prepareStatement("select * from student");
        // 查询
        final ResultSet set = pre.executeQuery();
        // 处理结果集
        while (set.next()) {
            final int sid = set.getInt("sid");
            final int sage = set.getInt("sage");
            final String sname = set.getString("sname");
            final float score = set.getFloat("score");
            final Timestamp sbirthday = set.getTimestamp("sbirthday");
            // 通过工厂模式创建对象
            final Student build = Student.builder()
                    .sid(sid)
                    .sage(sage)
                    .sname(sname)
                    .score(score)
                    .sbirthday(sbirthday)
                    .build();
            // 添加
            students.add(build);
        }
        // 关闭连接
        JdbcUtil.close(con, set, pre);
        return students;
    }
}
